﻿using MCPlatform.Communicate.SerialPorts;
using MCPlatform.MotionLib.Base.Environment;
using MCPlatform.Shared.Enums;
using MCPlatform.Test.Communicate;
using MCPlatform.Test.ParsingDLL;
using Microsoft.AspNetCore.Mvc.Infrastructure;
using Panuon.WPF.UI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Security.Permissions;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Markup;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace MCPlatform.Test
{
    public class TestBuilder
    {
        #region Properties

        public ISerialPort SerialPort { get; set; }

       
        public bool IsLowerTempe
        {
            get 
            {
                var lines = File.ReadAllLines(Paths.NumberProbeTempeConfigPaths);

                foreach (var line in lines)
                {
                    var parts = line.Split(new[] { ':' }, 2);
                    if (parts.Length != 2) continue;

                    var name = parts[0].Trim();
                    var value = parts[1].Trim();

                    if (value.Contains("True"))
                    {
                        return true;
                    }

                }
                return false; 
            }
           
        }



        public static event Action<ProbeStatus,int, bool[]?>? ProbeStatusEvent;

        public static event Action<ProbeStatus, int>? ProbeStatusBusyEvent;


        public Dictionary<string, string>? BasicConfig { get; set; }

        public Dictionary<string, string>? CalibrateConfig { get; set; }

        public Dictionary<int, double>? VT_Table { get; set; }


        public TestBoardCommunicate TestBoardCommunicate { get; set; }



        #endregion

        #region events


        public event Action<string>? TestInfoEvent;

      

        #endregion

        #region CTOR

        public TestBuilder(ISerialPort serialPort)
        {
            SerialPort = serialPort;
            TestBoardCommunicate = new TestBoardCommunicate(SerialPort);
        }

        #endregion
        public async Task<(bool, bool[]?)> TestExecute(int SerialPortId,int productId,AutoResetEvent autoResetEvent, Action<bool> waitOneCallBack, CancellationToken cancellationToken)
        {
          
            ProductTypeEnum productType = (ProductTypeEnum)productId;

            if (productType == ProductTypeEnum.阵列)
            {
               return await ArrayTestExecute(SerialPortId, autoResetEvent, waitOneCallBack, cancellationToken);
            }
            else if(productType == ProductTypeEnum.数字探头)
            {
               return await NumberProbeTestExecute(SerialPortId,autoResetEvent, waitOneCallBack, cancellationToken);
            }
            return (false, null);
        }


        /// <summary>
        /// 阵列测试
        /// </summary>
        /// <param name="id"></param>
        /// <param name="autoResetEvent"></param>
        /// <param name="waitOneCallBack"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<(bool, bool[]?)> ArrayTestExecute(int id, AutoResetEvent autoResetEvent, Action<bool> waitOneCallBack,CancellationToken cancellationToken)
        {
            autoResetEvent.Reset();

            bool testResult = false;

            //获取阵列配置

            var cofigData = GetArrayProbeConfig();

            TestBoardCommunicate testBoardCommunicate = new TestBoardCommunicate(SerialPort);

            //创建12个产品对象          

            List<ThermopileTest> thermopileTestList = new List<ThermopileTest>();
            for (int i = 0; i < 12; i++)
            {
                thermopileTestList.Add(new ThermopileTest());
            }

            try
            {

                //1.先ping板卡看是否通讯成功
                var pingResponse = await PingCommandAsync(testBoardCommunicate,cancellationToken);
              
                //2.读探头状态指令
               
                var initialResponse = await InitialAndGetProbeStatusAsync(cofigData.u8Reg,testBoardCommunicate, cancellationToken);

                //3.获取配置信息
                
                var probeStatus = initialResponse.Item1;

                var compareResult = CompareArrays(pingResponse, probeStatus);

                //更新12个产品配置至内部存储区

                StoreConfigDataFromSensorEEP(initialResponse.Item2,thermopileTestList, cancellationToken);
            
                //4.开始采样
               
                var samplingResult = await StartSamplingAsync(1,testBoardCommunicate, cancellationToken);

                
                //5.七秒后停止采样
                await Task.Delay(7000);
               
                var samplingResponse = await StopSamplingAndGetSamplingDataAsync(1,testBoardCommunicate, cancellationToken);
               
                probeStatus = samplingResponse.Item1;

                compareResult = CompareArrays(probeStatus, compareResult);


                //6.保存探头采样数据
                //保存12个探头采样数据

                SaveSampledData(1,25,samplingResponse.Item2,thermopileTestList, cancellationToken);
               
                //通知已暂停
                TestInfoEvent?.Invoke("等待第二个温度采样点到达");
                waitOneCallBack?.Invoke(true);
                autoResetEvent.WaitOne();

                //7.第二个测试温度点，开始采样
                 samplingResult = await StartSamplingAsync(2, testBoardCommunicate, cancellationToken);

                //8.七秒后停止采样

                await Task.Delay(7000);
                
                samplingResponse = await StopSamplingAndGetSamplingDataAsync(2, testBoardCommunicate, cancellationToken);

                probeStatus = samplingResponse.Item1;

                compareResult = CompareArrays(probeStatus, compareResult);

                //9.保存探头采样数据
                //保存12个探头采样数据
                SaveSampledData(2, 100, samplingResponse.Item2, thermopileTestList, cancellationToken);

                //通知已暂停
                TestInfoEvent?.Invoke("等待第三个温度采样点到达");
                waitOneCallBack?.Invoke(true);
                autoResetEvent.WaitOne();

                //10.第三个个测试温度点，开始采样
                samplingResult = await StartSamplingAsync(3, testBoardCommunicate, cancellationToken);

                //11.七秒后停止采样
                await Task.Delay(7000);
                samplingResponse = await StopSamplingAndGetSamplingDataAsync(3, testBoardCommunicate, cancellationToken);

                probeStatus = samplingResponse.Item1;

                compareResult = CompareArrays(probeStatus, compareResult);

                //12.保存探头采样数据
                //保存12个探头采样数据
                SaveSampledData(3, 250, samplingResponse.Item2, thermopileTestList, cancellationToken);

                //13.生成修正值
               
                probeStatus = await SetAllProbesPixelCorrectionCoefficientAsync(testBoardCommunicate, thermopileTestList, cancellationToken);

                compareResult = CompareArrays(probeStatus, compareResult);

                //15.生成系数和坏点信息

                probeStatus = await SetAllProbesCoefficientAndBadPointInfoAsync(testBoardCommunicate, thermopileTestList, cancellationToken);

                compareResult = CompareArrays(probeStatus, compareResult);

                //16.生成配置内容并写入板卡

                probeStatus = await SetProbeEEPROMConfigAsync(testBoardCommunicate, thermopileTestList, cancellationToken);

                compareResult = CompareArrays(probeStatus, compareResult);


                //17.结束测试
                TestInfoEvent?.Invoke("结束测试");
                probeStatus = await testBoardCommunicate.EndWorkAsync();

                compareResult = CompareArrays(probeStatus, compareResult);

                testResult = true;
                return (true, probeStatus);

            }
            catch (Exception)
            {

                throw;
            }
            finally
            {
                if (!testResult)
                {
                    waitOneCallBack?.Invoke(testResult);
                }

                foreach (ThermopileTest test in thermopileTestList)
                {
                    test?.Dispose();
                }
            }


        }


        public async Task<bool[]?> Test(int productId)
        {
            TestBoardCommunicate testBoardCommunicate = new TestBoardCommunicate(SerialPort);


            //  await NumberProbeTestExecute();
            //var PasingTxt = new ParsingProbeConfigTxt();
            //var cofigData = PasingTxt.GetData();

            //var basicConfig = PasingTxt.GetBasicConfig();


            //var calibrateConfig = PasingTxt.GetCalibrateParameterConfig();


            //var table = PasingTxt.GetVtTable();

            //  await testBoardCommunicate.InitialProbesAndConfigsTO1_TAAsync();

            //await testBoardCommunicate.ClearOffsetCalibraCoefficientAsync();


            //await testBoardCommunicate.ClearAmbientTempeCalibraCoefficientAsync();

            //await testBoardCommunicate.ClearGainCalibraCoefficientAsync();

            ////await testBoardCommunicate.CalibrateOffsetAsync(0, 100);

            //await testBoardCommunicate.PauseSamplingAmbientTempeAndTargetTempeAsync();



            TestInfoEvent?.Invoke("获取探头配置状态");
            // var response = await testBoardCommunicate.InitialAndGetProbeStatusAsync(cofigData.u8Reg);

            //return response.Item1;


            return await testBoardCommunicate.Test(productId);
        }


        /// <summary>
        /// 数字探头测试
        /// </summary>
        /// <param name="id"></param>
        /// <param name="autoResetEvent"></param>
        /// <param name="waitOneCallBack"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<(bool, bool[]?)>  NumberProbeTestExecute(int id, AutoResetEvent autoResetEvent, Action<bool> waitOneCallBack,CancellationToken cancellationToken)
        {

            autoResetEvent.Reset();
            bool testResult = false;

            try
            {
                bool getConfigResult = GetNumberProbeConfig();

                if (!getConfigResult)
                {
                    MessageBoxX.Show("获取探头配置信息失败!", "提示");
                    return(false,null);
                }


                TestBoardCommunicate = new TestBoardCommunicate(SerialPort);
                TestBoardCommunicate.SerialPortID = id;

                //1.先ping板卡看是否通讯成功

                var pingResult = await PingCommandAsync(TestBoardCommunicate, cancellationToken);
             

                //2.初始化板卡
                var probeStatus = await InitialProbesAndConfigsTO1_TAAsync(TestBoardCommunicate, cancellationToken);


                var compareResult = CompareArrays(pingResult, probeStatus);

                //3.保存数据

                probeStatus = await SaveEEBlowDataAsync(TestBoardCommunicate, cancellationToken);

                compareResult = CompareArrays(compareResult, probeStatus);

                //4.写入VT表
                probeStatus = await WriteVtTableAsync(TestBoardCommunicate, BasicConfig, VT_Table, cancellationToken);

                compareResult = CompareArrays(compareResult, probeStatus);

                //保存
                probeStatus = await SaveEEBlowDataAsync(TestBoardCommunicate, cancellationToken);

                compareResult = CompareArrays(compareResult, probeStatus);

                //5.清除环境校准系数

                probeStatus = await ClearAmbientTempeCalibraCoefficientAsync(TestBoardCommunicate, cancellationToken);

                compareResult = CompareArrays(compareResult, probeStatus);

                //6.采集目标环境温度
                var readTempResult = await ReadAmbientTempeAndTargetTempeAsync(TestBoardCommunicate, cancellationToken);
                probeStatus = readTempResult.Item1;
                compareResult = CompareArrays(compareResult, probeStatus);

                //7.校准环境温度系数

                probeStatus = await CalibrateAmbientTempeAsync(TestBoardCommunicate, CalibrateConfig, cancellationToken);
                compareResult = CompareArrays(compareResult, probeStatus);
                //8.保存数据指令
                probeStatus = await SaveEEBlowDataAsync(TestBoardCommunicate, cancellationToken);
                compareResult = CompareArrays(compareResult, probeStatus);

                //9.清除offset校准系数
                probeStatus = await ClearOffsetCalibraCoefficientAsync(TestBoardCommunicate, cancellationToken);
                compareResult = CompareArrays(compareResult, probeStatus);

                //10.校准offset
                probeStatus = await CalibrateOffsetAsync(TestBoardCommunicate, CalibrateConfig, cancellationToken);
                compareResult = CompareArrays(compareResult, probeStatus);
                //11.保存数据指令
                probeStatus = await SaveEEBlowDataAsync(TestBoardCommunicate, cancellationToken);
                compareResult = CompareArrays(compareResult, probeStatus);
                //这里运行到150度遮光板位置
                waitOneCallBack?.Invoke(true);
                autoResetEvent.WaitOne();


                //12.清除gain校准系数
                probeStatus = await ClearGainCalibraCoefficientAsync(TestBoardCommunicate, cancellationToken);
                compareResult = CompareArrays(compareResult, probeStatus);

                //13.校准gain
                probeStatus = await CalibrateGainAsync(TestBoardCommunicate, CalibrateConfig, cancellationToken);
                compareResult = CompareArrays(compareResult, probeStatus);

                //14.保存数据指令
                probeStatus = await SaveEEBlowDataAsync(TestBoardCommunicate, cancellationToken);
                compareResult = CompareArrays(compareResult, probeStatus);

                //15.开始采集温度(比对150度情况)
                ProbeStatusBusyEvent?.Invoke(ProbeStatus.TargetTempe, id);
                readTempResult = await ReadAmbientTempeAndTargetTempeAsync(TestBoardCommunicate, cancellationToken);
                probeStatus = readTempResult.Item1;
                compareResult = CompareArrays(compareResult, probeStatus);
                //比较温度范围是不是在正负2度
                probeStatus = CompareTemp(readTempResult.Item2,150,2);
                //比较结果
                ProbeStatusEvent?.Invoke(ProbeStatus.TargetTempe, id, probeStatus);

                compareResult = CompareArrays(compareResult, probeStatus);



                //16.停止采集
                probeStatus = await PauseSamplingAmbientTempeAndTargetTempeAsync(TestBoardCommunicate, cancellationToken);
                compareResult = CompareArrays(compareResult, probeStatus);


                //这里运行到100度遮光板位置
                waitOneCallBack?.Invoke(true);
                autoResetEvent.WaitOne();
                //17.采集温度（比对100度温度）
                ProbeStatusBusyEvent?.Invoke(ProbeStatus.Target100Tempe, id);
                readTempResult = await ReadAmbientTempeAndTargetTempeAsync(TestBoardCommunicate, cancellationToken);
                probeStatus = readTempResult.Item1;
                compareResult = CompareArrays(compareResult, probeStatus);
                //比较温度范围是不是在正负2度
                probeStatus = CompareTemp(readTempResult.Item2, 150, 2);

                //比较结果
                ProbeStatusEvent?.Invoke(ProbeStatus.Target100Tempe, id, probeStatus);

                compareResult = CompareArrays(compareResult, probeStatus);

                ProbeStatusEvent?.Invoke(ProbeStatus.Result, id, compareResult);

                testResult = true;

                return (true, null);
            }
            catch (OperationCanceledException ex)
            {
                throw ex;
            }
            catch (Exception)
            {

                throw;
            }
            finally
            {
                if (!testResult)
                {
                    waitOneCallBack?.Invoke(testResult);
                }
            }
            
            



        }

        public async Task InitialBasicConfig()
        {
            bool getConfigResult = GetNumberProbeConfig();

            if (!getConfigResult)
            {
                MessageBoxX.Show("获取探头配置信息失败!", "提示");
                return;
            }


            TestBoardCommunicate = new TestBoardCommunicate(SerialPort);
                     

            //2.初始化板卡
            var probeStatus = await InitialProbesAndConfigsTO1_TAAsync(TestBoardCommunicate, new CancellationToken());

            probeStatus = await SaveEEBlowDataAsync(TestBoardCommunicate, new CancellationToken());

            probeStatus = await WriteVtTableAsync(TestBoardCommunicate, BasicConfig, VT_Table, new CancellationToken());

            probeStatus = await SaveEEBlowDataAsync(TestBoardCommunicate, new CancellationToken());
        }

        #region Auxiliary Methods


        public bool[] CompareTemp(Dictionary<ushort, byte[]>? datas,double temp,double error)
        {
            bool[] result = new bool[12];
            if (datas is null)
            {
                return result;
            }

           
            foreach (var data in datas)
            {
                int probeNumber = data.Key;
                var probeData = data.Value;               
                var ta = GetFloatData(probeData, 0);
                var to = GetFloatData(probeData, 1);
                var rawAdc = GetFloatData(probeData, 2);
                var calAdc = GetFloatData(probeData, 3);

                if (result.Length > probeNumber)
                {
                    result[probeNumber] = Math.Abs(ta - temp) <= error;
                }
                

            }

            return result;

        }


        private float GetFloatData(byte[] datas, int dataIndex)
        {
            var data = SplitArray(datas, 4);
            return ByteArrayToFloat(data[dataIndex]);

        }


        public static float ByteArrayToFloat(byte[] bytes)
        {

            // 如果需要转换为大端字节顺序  
            if (BitConverter.IsLittleEndian)
            {
                Array.Reverse(bytes, 0, 4); // 反转四个字节的顺序  
            }

            // 现在字节数组以大端字节顺序存储，或者如果系统本身是大端的，则无需更改  
            return BitConverter.ToSingle(bytes, 0);
        }

        static byte[][] SplitArray(byte[] array, int parts)
        {
            if (array.Length % parts != 0)
                throw new ArgumentException("Array length must be divisible by parts.");

            byte[][] result = new byte[parts][];
            int partSize = array.Length / parts;

            for (int i = 0; i < parts; i++)
            {
                byte[] part = new byte[partSize];
                Array.Copy(array, i * partSize, part, 0, partSize);
                result[i] = part;
            }

            return result;
        }


        public static bool[] CompareArrays(bool[]? array1, bool[]? array2)
        {
            if (array1 is null || array2 is null)
            {               
                return new bool[12];
            }
            int length = Math.Min(array1.Length, array2.Length);
            bool[] comparedArray = new bool[length];

            for (int i = 0; i < length; i++)
            {
                comparedArray[i] = array1[i] && array2[i];
            }

            return comparedArray;
        }


        #endregion

        #region Methods of Array Probes

        /// <summary>
        /// 获取阵列配置
        /// </summary>
        /// <returns></returns>
        public StrMTPA16DefaultConfidData GetArrayProbeConfig()
        {
            TestInfoEvent?.Invoke("读取阵列探头配置txt文件");
            var PasingTxt = new ParsingProbeConfigTxt();
            return PasingTxt.GetData();           
        }

        /// <summary>
        /// 初始化探头配置
        /// </summary>
        /// <param name="u8Reg"></param>
        /// <param name="testBoardCommunicate"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="OperationCanceledException"></exception>
        public async Task<(bool[]?, Dictionary<ushort, byte[]>?)> InitialAndGetProbeStatusAsync(byte[] u8Reg,TestBoardCommunicate testBoardCommunicate, CancellationToken cancellationToken)
        {
            if (cancellationToken.IsCancellationRequested)
            {
                throw new OperationCanceledException();
            }
            TestInfoEvent?.Invoke("获取探头配置状态");
            var response = await testBoardCommunicate.InitialAndGetProbeStatusAsync(u8Reg);
            if (response.Item2 is null)
            {
                TestInfoEvent?.Invoke("获取探头配置状态失败");
            }

            return response;
        }

        /// <summary>
        /// 更新12个探头产品配置至内部存储区
        /// </summary>
        /// <param name="cofigData"></param>
        /// <param name="thermopileTestList"></param>
        /// <param name="cancellationToken"></param>
        /// <exception cref="OperationCanceledException"></exception>
        public void StoreConfigDataFromSensorEEP(Dictionary<ushort, byte[]>? cofigData ,List<ThermopileTest> thermopileTestList,CancellationToken cancellationToken)
        {
            if (cancellationToken.IsCancellationRequested)
            {
                throw new OperationCanceledException();
            }

            if (cofigData is null)
            {
                TestInfoEvent?.Invoke("12个探头产品配置为空");
                return;
            }
            TestInfoEvent?.Invoke("更新12个探头产品配置至内部存储区");
            foreach (ThermopileTest test in thermopileTestList)
            {
                int index = thermopileTestList.IndexOf(test);
                test.StoreConfigDataFromSensorEEP(cofigData[(ushort)index]);
               
            }
        }

        /// <summary>
        /// 开始温度采样
        /// </summary>
        /// <param name="testBoardCommunicate"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<bool> StartSamplingAsync(int times,TestBoardCommunicate testBoardCommunicate,CancellationToken cancellationToken)
        {
            if (cancellationToken.IsCancellationRequested)
            {
                throw new OperationCanceledException();
            }

            TestInfoEvent?.Invoke($"开始第{times}个温度采样");
            var samplingResult = await testBoardCommunicate.StartSamplingAsync();
            if (!samplingResult)
            {
                TestInfoEvent?.Invoke($"第{times}个温度采样失败！");
                return false;
            }

            return true;
        }

        /// <summary>
        /// 停止温度采样
        /// </summary>
        /// <param name="testBoardCommunicate"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="OperationCanceledException"></exception>

        public async Task<(bool[]?, Dictionary<ushort, byte[]>?)> StopSamplingAndGetSamplingDataAsync(int times, TestBoardCommunicate testBoardCommunicate, CancellationToken cancellationToken)
        {
            if (cancellationToken.IsCancellationRequested)
            {
                throw new OperationCanceledException();
            }

            TestInfoEvent?.Invoke($"停止第{times}个温度采样");
            return await testBoardCommunicate.StopSamplingAndGetSamplingDataAsync();
            
        }

        /// <summary>
        /// 保存探头采样点数据
        /// </summary>
        /// <param name="CaliPointID"></param>
        /// <param name="Temp"></param>
        /// <param name="sampledData"></param>
        /// <param name="thermopileTestList"></param>
        /// <param name="cancellationToken"></param>
        /// <exception cref="OperationCanceledException"></exception>
        public void SaveSampledData(int CaliPointID, float Temp,Dictionary<ushort, byte[]>? sampledData, List<ThermopileTest> thermopileTestList, CancellationToken cancellationToken)
        {
            if (cancellationToken.IsCancellationRequested)
            {
                throw new OperationCanceledException();
            }

            if (sampledData is null)
            {
                TestInfoEvent?.Invoke("探头采样点数据为空！");
                return;
            }

            TestInfoEvent?.Invoke("保存探头采样点数据");
            foreach (ThermopileTest test in thermopileTestList)
            {
                int index = thermopileTestList.IndexOf(test);
                test.SaveSampledData(CaliPointID, Temp, sampledData[(ushort)index]);
            }
        }


        /// <summary>
        /// 生成修正值
        /// </summary>
        /// <param name="testBoardCommunicate"></param>
        /// <param name="thermopileTestList"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async  Task<bool[]?> SetAllProbesPixelCorrectionCoefficientAsync(TestBoardCommunicate testBoardCommunicate,List<ThermopileTest> thermopileTestList, CancellationToken cancellationToken)
        {
            TestInfoEvent?.Invoke("生成修正值");
            List<byte> pixelCorrectionCoefficientBytes = new List<byte>();
            foreach (ThermopileTest test in thermopileTestList)
            {
                int index = thermopileTestList.IndexOf(test);
                byte[] _PixelCorrectionCoefficient = new byte[3074];
                test.Calculate_PixelCorrectionCoefficient(_PixelCorrectionCoefficient);
                test.ExportPixCoeffAndCS(_PixelCorrectionCoefficient);
                pixelCorrectionCoefficientBytes.AddRange(_PixelCorrectionCoefficient);
            }

            //写入修正值至板卡
            TestInfoEvent?.Invoke("修正值写入至板卡");
            return await testBoardCommunicate.SetAllProbesPixelCorrectionCoefficientAsync(pixelCorrectionCoefficientBytes.ToArray());
        }

        /// <summary>
        /// 生成系数和坏点信息
        /// </summary>
        /// <param name="testBoardCommunicate"></param>
        /// <param name="thermopileTestList"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<bool[]?> SetAllProbesCoefficientAndBadPointInfoAsync(TestBoardCommunicate testBoardCommunicate, List<ThermopileTest> thermopileTestList, CancellationToken cancellationToken)
        {
            TestInfoEvent?.Invoke("生成系数和坏点信息");
            List<byte> coeffAndDPixDataBytes = new List<byte>();
            foreach (ThermopileTest test in thermopileTestList)
            {
                int index = thermopileTestList.IndexOf(test);
                byte[] _CoeffAndDPixData = new byte[208];
                test.ExportCoeffAndDPixData(_CoeffAndDPixData);
                coeffAndDPixDataBytes.AddRange(_CoeffAndDPixData);
            }

            //生成系数和坏点信息写入板卡
            TestInfoEvent?.Invoke("系数和坏点信息写入板卡");
            return await testBoardCommunicate.SetAllProbesCoefficientAndBadPointInfoAsync(coeffAndDPixDataBytes.ToArray());
        }


        public async Task<bool[]?> SetProbeEEPROMConfigAsync(TestBoardCommunicate testBoardCommunicate, List<ThermopileTest> thermopileTestList, CancellationToken cancellationToken)
        {
            TestInfoEvent?.Invoke("生成配置内容");
            List<byte> configInfoDataBytes = new List<byte>();
            foreach (ThermopileTest test in thermopileTestList)
            {
                int index = thermopileTestList.IndexOf(test);
                byte[] _ConfigInfoData = new byte[128];
                test.ExportConfigInfoData(_ConfigInfoData);
                configInfoDataBytes.AddRange(_ConfigInfoData);
            }

            //生成配置内容并写入板卡写入板卡
            TestInfoEvent?.Invoke("配置内容写入板卡");
            return await testBoardCommunicate.SetProbeEEPROMConfigAsync(configInfoDataBytes.ToArray());
        }


        #endregion

        #region Methods of Number Probes

        /// <summary>
        /// 获取探头配置
        /// </summary>
        /// <returns></returns>
        public bool GetNumberProbeConfig()
        {
            //0.读取配置信息
            TestInfoEvent?.Invoke("获取探头配置");
            
           
            string? path = null;
            if (IsLowerTempe)
            {
                path = Paths.NumberProbeLowerTempeConfigPaths;
            }

            var PasingTxt = new ParsingProbeConfigTxt();



            BasicConfig = PasingTxt.GetBasicConfig(path);

            CalibrateConfig = PasingTxt.GetCalibrateParameterConfig(path);

            VT_Table = PasingTxt.GetVtTable(path);


            if (BasicConfig is null || CalibrateConfig is null || VT_Table is null)
            {

                return false;
            }

            return true;
        }

       
        /// <summary>
        /// ping板卡
        /// </summary>
        /// <param name="testBoardCommunicate">串口模块</param>
        /// <param name="cancellationToken">任务令牌</param>
        /// <returns>探头状态</returns>
        public async Task<bool[]?> PingCommandAsync(TestBoardCommunicate testBoardCommunicate, CancellationToken cancellationToken)
        {
            if (cancellationToken.IsCancellationRequested)
            {
                throw new OperationCanceledException();
            }

            TestInfoEvent?.Invoke("正在ping板卡确认是否通讯成功");

            ProbeStatusBusyEvent?.Invoke(ProbeStatus.Ready, testBoardCommunicate.SerialPortID);
            //1.先ping板卡看是否通讯成功
            var pingResult = await testBoardCommunicate.PingCommandAsync();
            bool[] bools = new bool[12];
            for (int i = 0; i < bools.Length; i++)
            {
                bools[i] = pingResult;
            }
            ProbeStatusEvent?.Invoke(ProbeStatus.Ready, testBoardCommunicate.SerialPortID, bools);
            return bools;
        }

        /// <summary>
        /// 初始化数字探头和配置
        /// </summary>
        /// <param name="testBoardCommunicate">串口模块</param>
        /// <param name="cancellationToken">任务令牌</param>
        /// <returns>探头状态</returns>
        public async Task<bool[]?> InitialProbesAndConfigsTO1_TAAsync(TestBoardCommunicate testBoardCommunicate, CancellationToken cancellationToken)
        {
            if (cancellationToken.IsCancellationRequested)
            {
                throw new OperationCanceledException();
            }
            ProbeStatusBusyEvent?.Invoke(ProbeStatus.Link, testBoardCommunicate.SerialPortID);
            var result = await testBoardCommunicate.InitialProbesAndConfigsTO1_TAAsync();
            ProbeStatusEvent?.Invoke(ProbeStatus.Link, testBoardCommunicate.SerialPortID, result);
            return result;
        }

        /// <summary>
        /// 保存EEBlow数据
        /// </summary>
        /// <param name="testBoardCommunicate">串口模块</param>
        /// <param name="cancellationToken">任务令牌</param>
        /// <returns>探头状态</returns>
        public async Task<bool[]?> SaveEEBlowDataAsync(TestBoardCommunicate testBoardCommunicate, CancellationToken cancellationToken)
        {
            if (cancellationToken.IsCancellationRequested)
            {
                throw new OperationCanceledException();
            }
            TestInfoEvent?.Invoke("保存EEBlow数据");
            return await testBoardCommunicate.SaveEEBlowDataAsync();


        }

        /// <summary>
        /// 写入VT表
        /// </summary>
        /// <param name="testBoardCommunicate"></param>
        /// <param name="basicConfig"></param>
        /// <param name="vtTable"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<bool[]?> WriteVtTableAsync(TestBoardCommunicate testBoardCommunicate, Dictionary<string, string>? basicConfig, Dictionary<int, double>? vtTable, CancellationToken cancellationToken)
        {
            if (cancellationToken.IsCancellationRequested || basicConfig is null)
            {
                throw new OperationCanceledException();
            }

            TestInfoEvent?.Invoke("写入VT表");

            List<string> tableHex = new List<string>();

            foreach (var item in vtTable!.Values)
            {

                if (basicConfig["Vt_scale"].Contains("16"))
                {
                    int val = (int)(item * 256 * 8 / 1000);
                    tableHex.AddRange(TestBoardCommunicate.IntToHexStringAtLeast2Byte(val));
                }
                else
                {
                    int val = (int)(item * 256 / 1000);
                    tableHex.AddRange(TestBoardCommunicate.IntToHexStringAtLeast2Byte(val));
                }

            }

            return await testBoardCommunicate.WriteVtTable(vtTable.Keys.Min(), vtTable.Keys.Max(), tableHex.ToArray());


        }

        /// <summary>
        /// 清除环境校准系数
        /// </summary>
        /// <param name="testBoardCommunicate">串口模块</param>
        /// <param name="cancellationToken">任务令牌</param>
        /// <returns>探头状态</returns>
        public async Task<bool[]?> ClearAmbientTempeCalibraCoefficientAsync(TestBoardCommunicate testBoardCommunicate, CancellationToken cancellationToken)
        {
            if (cancellationToken.IsCancellationRequested)
            {
                throw new OperationCanceledException();
            }

            TestInfoEvent?.Invoke("清除环境校准系数");
            return await testBoardCommunicate.ClearAmbientTempeCalibraCoefficientAsync();

        }


        /// <summary>
        /// 读取环境温度和目标温度
        /// </summary>
        /// <param name="testBoardCommunicate">串口模块</param>
        /// <param name="cancellationToken">任务令牌</param>
        /// <returns>探头状态</returns>
        public async Task<(bool[]?, Dictionary<ushort, byte[]>?)> ReadAmbientTempeAndTargetTempeAsync(TestBoardCommunicate testBoardCommunicate, CancellationToken cancellationToken)
        {
            

            if (cancellationToken.IsCancellationRequested)
            {
                throw new OperationCanceledException();
            }
            TestInfoEvent?.Invoke("读取环境温度和目标温度");
           // ProbeStatusBusyEvent?.Invoke(probeStatus, testBoardCommunicate.SerialPortID);
            var result = await testBoardCommunicate.ReadAmbientTempeAndTargetTempeAsync();
           // ProbeStatusEvent?.Invoke(probeStatus, testBoardCommunicate.SerialPortID, result.Item1);
            return result;

        }


        public async Task<(bool[]?, Dictionary<ushort, byte[]>?)> ReadAmbientTempeAndTargetTempeAsync( CancellationToken cancellationToken)
        {
            

            if (cancellationToken.IsCancellationRequested)
            {
                throw new OperationCanceledException();
            }
            try
            {
                TestInfoEvent?.Invoke("读取环境温度和目标温度");
                //ProbeStatusBusyEvent?.Invoke(ProbeStatus.TargetTempe, TestBoardCommunicate.SerialPortID);
                var result = await TestBoardCommunicate.ReadAmbientTempeAndTargetTempeAsync();
               // ProbeStatusEvent?.Invoke(ProbeStatus.TargetTempe, TestBoardCommunicate.SerialPortID, result.Item1);
                return result;
            }
            catch (Exception)
            {

                throw;
            }
            

        }


        /// <summary>
        /// 校准环境温度
        /// </summary>
        /// <param name="testBoardCommunicate">串口模块</param>
        /// <param name="calibrateConfig">校准配置</param>
        /// <param name="cancellationToken">任务令牌</param>
        /// <returns>探头状态</returns>
        public async Task<bool[]?> CalibrateAmbientTempeAsync(TestBoardCommunicate testBoardCommunicate, Dictionary<string, string>? calibrateConfig, CancellationToken cancellationToken)
        {
            if (cancellationToken.IsCancellationRequested || calibrateConfig is null)
            {
                throw new OperationCanceledException();
            }
            TestInfoEvent?.Invoke("校准环境温度！");

            ProbeStatusBusyEvent?.Invoke(ProbeStatus.TempetureCal, testBoardCommunicate.SerialPortID);

            int.TryParse(calibrateConfig["CalibraEnvCollectFrequency"], out int frequency);

            string key = "CalibraEnvTemperature";
            if (!calibrateConfig.ContainsKey(key))
            {
                // 如果字典中没有这个键，则添加新的键值对
                calibrateConfig.Add(key, "25");              
            }
           
            int.TryParse(calibrateConfig["CalibraEnvTemperature"], out int calibraEnvTemperature);

            var result = await testBoardCommunicate.CalibrateAmbientTempeAsync(calibraEnvTemperature, frequency);
            ProbeStatusEvent?.Invoke(ProbeStatus.TempetureCal, testBoardCommunicate.SerialPortID, result);


            return result;

        }

        /// <summary>
        /// 清除offset校准系数
        /// </summary>
        /// <param name="testBoardCommunicate">串口模块</param>
        /// <param name="cancellationToken">任务令牌</param>
        /// <returns>探头状态</returns>
        public async Task<bool[]?> ClearOffsetCalibraCoefficientAsync(TestBoardCommunicate testBoardCommunicate, CancellationToken cancellationToken)
        {
            if (cancellationToken.IsCancellationRequested)
            {
                throw new OperationCanceledException();
            }

            TestInfoEvent?.Invoke("清除offset校准系数");
            return await testBoardCommunicate.ClearOffsetCalibraCoefficientAsync();

        }


        /// <summary>
        /// 校准offset
        /// </summary>
        /// <param name="testBoardCommunicate">串模块</param>
        /// <param name="calibrateConfig">校准配置</param>
        /// <param name="cancellationToken">任务令牌</param>
        /// <returns></returns>
        public async Task<bool[]?> CalibrateOffsetAsync(TestBoardCommunicate testBoardCommunicate, Dictionary<string, string>? calibrateConfig, CancellationToken cancellationToken)
        {
            if (cancellationToken.IsCancellationRequested || calibrateConfig is null)
            {
                throw new OperationCanceledException();
            }

            TestInfoEvent?.Invoke("校准offset");

            ProbeStatusBusyEvent?.Invoke(ProbeStatus.OffsetCal, testBoardCommunicate.SerialPortID);

            int.TryParse(calibrateConfig["OffsetVoltageValue"], out int offsetVoltageValue);
            int.TryParse(calibrateConfig["OffsetCollectFrequency"], out int offsetCollectFrequency);
            var result = await testBoardCommunicate.CalibrateOffsetAsync(offsetVoltageValue, offsetCollectFrequency);
            ProbeStatusEvent?.Invoke(ProbeStatus.OffsetCal, testBoardCommunicate.SerialPortID, result);


            return result;

        }

        /// <summary>
        /// 清除增益校准系数
        /// </summary>
        /// <param name="testBoardCommunicate">串口模块</param>
        /// <param name="cancellationToken">任务令牌</param>
        /// <returns>探头状态</returns>
        public async Task<bool[]?> ClearGainCalibraCoefficientAsync(TestBoardCommunicate testBoardCommunicate, CancellationToken cancellationToken)
        {
            if (cancellationToken.IsCancellationRequested)
            {
                throw new OperationCanceledException();
            }

            TestInfoEvent?.Invoke("清除增益校准系数");

            return await testBoardCommunicate.ClearGainCalibraCoefficientAsync();

        }

        /// <summary>
        /// 校准增益
        /// </summary>
        /// <param name="testBoardCommunicate">串口模块</param>
        /// <param name="calibrateConfig">校准配置</param>
        /// <param name="cancellationToken">任务令牌</param>
        /// <returns>探头状态</returns>
        public async Task<bool[]?> CalibrateGainAsync(TestBoardCommunicate testBoardCommunicate, Dictionary<string, string>? calibrateConfig, CancellationToken cancellationToken)
        {
            if (cancellationToken.IsCancellationRequested || calibrateConfig is null)
            {
                throw new OperationCanceledException();
            }
            TestInfoEvent?.Invoke("校准增益");

            ProbeStatusBusyEvent?.Invoke(ProbeStatus.GainCal, testBoardCommunicate.SerialPortID);
            int.TryParse(calibrateConfig["GainVoltageValue"], out int gainVoltageValue);
            int.TryParse(calibrateConfig["GainCollectFrequency"], out int gainCollectFrequency);
            var result = await testBoardCommunicate.CalibrateGainAsync(gainVoltageValue, gainCollectFrequency);
            ProbeStatusEvent?.Invoke(ProbeStatus.GainCal, testBoardCommunicate.SerialPortID, result);
            return result;
        }

        /// <summary>
        /// 停止采集环境温度和目标温度
        /// </summary>
        /// <param name="testBoardCommunicate">串口模块</param>
        /// <param name="cancellationToken">任务令牌</param>
        /// <returns>探头状态</returns>
        public async Task<bool[]?> PauseSamplingAmbientTempeAndTargetTempeAsync(TestBoardCommunicate testBoardCommunicate, CancellationToken cancellationToken)
        {
            if (cancellationToken.IsCancellationRequested)
            {
                throw new OperationCanceledException();

            }
            TestInfoEvent?.Invoke("停止采集环境温度和目标温度！");

            return await testBoardCommunicate.PauseSamplingAmbientTempeAndTargetTempeAsync();

        }



        #endregion


    }
}
